import { ApiEnum } from '@renderer/enum/ApiEnum'
import { CacheEnum } from '@renderer/enum/CacheEnum'
import { http } from '@renderer/plugins/axios'
import { reactive } from 'vue'
import useStorage from './useStorage'
import useUtil from './useUtil'
import { ElMessage } from 'element-plus'

const storage = useStorage()
export default () => {
  const form = reactive({
    account: '',
    password: '',
    code: '',
  })
  async function isLogin(): Promise<boolean> {
    const token = await storage.get(CacheEnum.TOKEN_NAME)
    return token
  }
  const login = useUtil().request(async () => {
    try {
      const { token } = await http.request<{ token: string }>({
        url: ApiEnum.LOGIN,
        method: 'POST',
        data: {
          account: form.account,
          password: form.password,
        },
      })
      loginInit(token)
    } catch (error) {
      console.log(error)
    }
  })
  const codeLogin = useUtil().request(async () => {
    try {
      const { token } = await http.request<{ token: string }>({
        url: ApiEnum.CODE_LOGIN,
        method: 'POST',
        data: {
          account: form.account,
          code: form.code,
        },
      })
      loginInit(token)
    } catch (error) {
      console.log(error)
    }
  })
  const sendSms = useUtil().request(async () => {
    try {
      await http.request({
        url: '/sendSms',
        method: 'POST',
        data: {
          account: form.account,
          scene: 'login',
        },
      })
      ElMessage({ type: 'success', message: '发送成功' })
    } catch (error) {
      console.log(error)
    }
  })
  const loginInit = async (token: string) => {
    await storage.set(CacheEnum.TOKEN_NAME, token)
    const res = await http.request<{ userInfo: UserModel; companyInfo: CompanyModel }>({
      url: ApiEnum.CURRENT_USER,
    })
    await storage.set(CacheEnum.USER_INFO, res.userInfo)
    await storage.set(CacheEnum.COMPANY_INFO, res.companyInfo)
    window.api.openWindow('config')
    window.api.closeWindow('login', 'destroy')
  }
  return { login, isLogin, form, codeLogin, sendSms, loginInit }
}
